<?php

/**
*  RainTPL
*  --------
*  Realized by Federico Ulfo & maintained by the Rain Team
*  Distributed under GNU/LGPL 3 License
*
*  @version 3.0 Alpha milestone: https://github.com/rainphp/raintpl3/issues/milestones?with_issues=no
*/


    /**
    * replace the path of image src, link href and a href.
    * url => template_dir/url
    * url# => url
    * http://url => http://url
    *
    * @param string $html
    * @return string html sostituito
    */
    function path_replace( $parameters, $conf ){
	// set variables
	$html = $parameters['code'];
	$template_basedir = $parameters['template_basedir'];
	$tags = $conf['plugins']['path_replace']['tags'];
	// get the template base directory
	$template_directory = $conf['base_url'] . $conf['tpl_dir'] . $template_basedir;
	// reduce the path
	$path = preg_replace('/\w+\/\.\.\//', '', $template_directory );
	$exp = $sub = array();
	
	if( in_array( "img", $tags ) ){
	    $exp = array( '/<img(.*?)src=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<img(.*?)src=(?:")([^"]+?)#(?:")/i', '/<img(.*?)src="(.*?)"/', '/<img(.*?)src=(?:\@)([^"]+?)(?:\@)/i' );
	    $sub = array( '<img$1src=@$2://$3@', '<img$1src=@$2@', '<img$1src="' . $path . '$2"', '<img$1src="$2"' );
	}
	
	if( in_array( "script", $tags ) ){
	    $exp = array_merge( $exp , array( '/<script(.*?)src=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<script(.*?)src=(?:")([^"]+?)#(?:")/i', '/<script(.*?)src="(.*?)"/', '/<script(.*?)src=(?:\@)([^"]+?)(?:\@)/i' ) );
	    $sub = array_merge( $sub , array( '<script$1src=@$2://$3@', '<script$1src=@$2@', '<script$1src="' . $path . '$2"', '<script$1src="$2"' ) );
	}
	
	if( in_array( "link", $tags ) ){
	    $exp = array_merge( $exp , array( '/<link(.*?)href=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<link(.*?)href=(?:")([^"]+?)#(?:")/i', '/<link(.*?)href="(.*?)"/', '/<link(.*?)href=(?:\@)([^"]+?)(?:\@)/i' ) );
	    $sub = array_merge( $sub , array( '<link$1href=@$2://$3@', '<link$1href=@$2@' , '<link$1href="' . $path . '$2"', '<link$1href="$2"' ) );
	}
	
	if( in_array( "a", $tags ) ){
	    $exp = array_merge( $exp , array( '/<a(.*?)href=(?:")(http\:\/\/|https\:\/\/|javascript:)([^"]+?)(?:")/i', '/<a(.*?)href="(.*?)"/', '/<a(.*?)href=(?:\@)([^"]+?)(?:\@)/i'  ) );
	    $sub = array_merge( $sub , array( '<a$1href=@$2$3@', '<a$1href="' . $conf['base_url'] . '$2"', '<a$1href="$2"' ) );
	}
	
	if( in_array( "input", $tags ) ){
	    $exp = array_merge( $exp , array( '/<input(.*?)src=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<input(.*?)src=(?:")([^"]+?)#(?:")/i', '/<input(.*?)src="(.*?)"/', '/<input(.*?)src=(?:\@)([^"]+?)(?:\@)/i' ) );
	    $sub = array_merge( $sub , array( '<input$1src=@$2://$3@', '<input$1src=@$2@', '<input$1src="' . $path . '$2"', '<input$1src="$2"' ) );
	}
	
	return preg_replace( $exp, $sub, $html );
	
    }